package com.hellobike.haxing.modules.order.service.impl;


import com.baomidou.mybatisplus.annotation.TableLogic;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.hellobike.haxing.common.constant.CommonConstant;
import com.hellobike.haxing.common.util.OrderUtils;
import com.hellobike.haxing.common.vo.Result;
import com.hellobike.haxing.modules.order.constant.OrderConstants;
import com.hellobike.haxing.modules.order.entity.*;
import com.hellobike.haxing.modules.order.mapper.OrderAftersaleMapper;
import com.hellobike.haxing.modules.order.mapper.OrderMapper;
import com.hellobike.haxing.modules.order.mapper.OrderRefundMapper;
import com.hellobike.haxing.modules.order.service.IOrderRefundService;

import org.jeecgframework.poi.excel.annotation.Excel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;


/**
 * @Description: 订单退款记录
 * @Author: haxing-boot
 * @Date:   2020-02-08
 * @Version: V1.0
 */
@Service
public class OrderRefundServiceImpl extends ServiceImpl<OrderRefundMapper, OrderRefund> implements IOrderRefundService {
    @Autowired
    private OrderUtils orderUtils;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderAftersaleMapper orderAftersaleMapper;
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveRefundAmount(OrderAftersale orderAfter) {
        //判断是否已经退款(申请中和退款成功)，已经申请中和退款成功不作处理
        QueryWrapper<OrderRefund> queryWrapper = new QueryWrapper();
        queryWrapper.lambda().eq(OrderRefund::getOrderAfterId,orderAfter.getId()).eq(OrderRefund::getDeleted, CommonConstant.DEL_FLAG_0)
                .eq(OrderRefund::getRefundStatus, OrderConstants.ORDER_STATUS_22);
        OrderRefund orderRefund= super.getOne(queryWrapper);
        if(orderRefund!=null){
            return;
        }
        //调用退款接口
        OrderRefund refund = new OrderRefund();
        refund.setAuditUser(orderAfter.getAuditUser());
        refund.setOrderAfterId(orderAfter.getId());
        refund.setOrderId(orderAfter.getOrderId());
        refund.setRefundAmount(orderAfter.getReturnAmount());
        refund.setRefundReason(orderAfter.getReason());
        refund.setRefundStatus(OrderConstants.ORDER_STATUS_20);
        refund.setAfterType(orderAfter.getAfterType());
        refund.setType(OrderConstants.ORDER_RETURN_AMOUNT_TYPE_0);
        refund.setBusinessNo(orderUtils.getReturnAmountBillNo(orderAfter.getAfterBillNo()));
        super.save(refund);

    }

    /**
     * 用户取消订单，审核通过
     * @param orderId
     * @param returnAmount
     * @param billNo
     */
    @Override
    public void saveRefundAmount(Long orderId, BigDecimal returnAmount, String billNo) {
        //  判断是否已经退款(申请中和退款成功)，已经申请中和退款成功不作处理
        QueryWrapper<OrderRefund> queryWrapper = new QueryWrapper();
        queryWrapper.lambda().eq(OrderRefund::getOrderId, orderId).eq(OrderRefund::getDeleted, OrderConstants.DEL_FLAG_0)
                .eq(OrderRefund::getRefundStatus, OrderConstants.ORDER_STATUS_22);
        OrderRefund orderRefund = super.getOne(queryWrapper);
        if (orderRefund != null) {
            return;
        }
        //调用退款接口
        OrderRefund refund = new OrderRefund();
        refund.setOrderId(orderId);
        refund.setRefundAmount(returnAmount);
        refund.setRefundReason("用户取消订单，审核通过");
        refund.setRefundStatus(OrderConstants.ORDER_STATUS_20);
        refund.setAfterType(OrderConstants.ORDER_AFTERSALE_TYPE_1);
        refund.setType(OrderConstants.ORDER_RETURN_AMOUNT_TYPE_1);
        refund.setBusinessNo(orderUtils.getReturnAmountBillNo(billNo));
        super.save(refund);
    }

    @Override
    public IPage<OrderRefund> queryPage(Page<OrderRefund> page, QueryWrapper<OrderRefund> queryWrapper) {
        return baseMapper.queryPage(page,queryWrapper);
    }

    @Override
    public Result<?> updateRefund(Long id) {
        OrderRefund orderRefund = super.getById(id);
        if(orderRefund==null) {
            return Result.error("未找到对应数据");
        }
        if(OrderConstants.ORDER_STATUS_22.equals(orderRefund.getRefundStatus())) {
            return Result.error("退款失败后才允许再次退款！");
        }
        //已退款或者退款中的金额
        BigDecimal refundSuccess= getBaseMapper().getSumRefundSuccess(orderRefund.getOrderId());
        Order order=orderMapper.selectById(orderRefund.getOrderId());
        //允许退款金额
        BigDecimal yrefund= order.getPayAmount().subtract(refundSuccess==null?BigDecimal.ZERO:refundSuccess);
        if(orderRefund.getRefundAmount().compareTo(yrefund)>0){
            return Result.ok("再次退款操作失败；退款金额大于可退款金额["+yrefund+"]元");
        }
        orderRefund.setRefundStatus(OrderConstants.ORDER_STATUS_20);
        if(OrderConstants.ORDER_RETURN_AMOUNT_TYPE_1.equals(orderRefund.getType())){
            orderRefund.setBusinessNo(orderUtils.getReturnAmountBillNo(order.getBillNo()));
        }else{
            String afterBillNo = orderAftersaleMapper.selectById(orderRefund.getOrderAfterId()).getAfterBillNo();
            orderRefund.setBusinessNo(orderUtils.getReturnAmountBillNo(afterBillNo));
        }
        super.updateById(orderRefund);
        return Result.ok("再次退款操作成功");
    }

}
